//
//  AmapExtentions.swift
//  amap
//
//  Created by James Karl on 2020/4/23.
//

import Foundation
import MAMapKit

extension CLLocationCoordinate2D {
    
    init?(json: [String: Double]) {
        if let lat = json["latitude"], let lon = json["longitude"] {
            self.init()
            self.latitude = lat
            self.longitude = lon
        } else {
            return nil
        }
    }
    
    func toLatLngData() -> LatLngData {
        return LatLngData(lat: latitude, lon: longitude)
    }
    
    func toMap() -> [String:Double] {
        return [
            "latitude" : latitude,
            "longitude" : longitude
        ]
    }
}

extension LatLngData {
    func toMapPoint()-> CLLocationCoordinate2D {
        return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
}

extension CGPoint {
    func toScreenPoint() -> ScreenPoint {
        return ScreenPoint(x: Int(x), y: Int(y))
    }
}

extension MAAnnotationView {
    func toMap() -> [String: Any?] {
        var m = [String: Any?]();
        m["alpha"] = Float(self.alpha)
        m["position"] = self.annotation.coordinate.toMap()
        m["title"]  = self.annotation.title
        m["snippet"] = self.annotation.subtitle
        return m;
    }
}

extension Int {
    func toUIColor() -> UIColor {
        let a = ((0xFF << 24) & self) >> 24
        let r = ((0xFF << 16) & self) >> 16
        let g = ((0xFF << 8 ) & self) >> 8
        let b = 0xff & self
        
        return UIColor(red: CGFloat(r) / 0xFF, green: CGFloat(g) / 0xFF, blue: CGFloat(b) / 0xFF, alpha: CGFloat(a) / 0xFF)
    }
}

extension MACoordinateRegion {
    func toMap() -> [String: Any?] {
        var m = [String: Any?]();
        m["farLeft"] = LatLngData(lat: center.latitude - self.span.latitudeDelta / 2, lon: center.longitude - self.span.longitudeDelta / 2).toMap()
        m["farRight"] = LatLngData(lat: center.latitude + self.span.latitudeDelta / 2, lon: center.longitude - self.span.longitudeDelta / 2).toMap()
        m["nearLeft"] = LatLngData(lat: center.latitude - self.span.latitudeDelta / 2, lon: center.longitude + self.span.longitudeDelta / 2).toMap()
        m["nearRight"] = LatLngData(lat: center.latitude + self.span.latitudeDelta / 2, lon: center.longitude + self.span.longitudeDelta / 2).toMap()
        m["latLngBounds"] = LatLngBoundsData(northeast: LatLngData(lat: center.latitude + self.span.latitudeDelta / 2, lon: center.longitude - self.span.longitudeDelta / 2) , southwest: LatLngData(lat: center.latitude - self.span.latitudeDelta / 2, lon: center.longitude + self.span.longitudeDelta / 2)).toMap()
        return m;
    }
}
